<?php defined('SYSPATH') or die('No direct script access.');

	class Jqgrid_Gridrequest{
		
		public $page;  // Get the requested page. By default grid sets this to 1. 
		public $limit; // get how many rows we want to have into the grid - rowNum parameter in the grid 
		public $sidx;  // get index row - i.e. user click to sort. At first time sortname parameter - after that the index from colModel
		public $sord;  // sorting order - at first time sortorder 
	
		private $records;
		private $total_pages;
		
		
		public function __construct($criteria = false){
			
			if ($criteria){
				$this->page = $criteria->page;
				$this->limit = $criteria->limit;
				$this->sidx = $criteria->sidx; // if we not pass at first time index use the first column for the index or what you want
				$this->sord = $criteria->sord;
			}else{
				$this->page = 1;
				$this->limit = 10;
				$this->sidx = 1; // if we not pass at first time index use the first column for the index or what you want
				$this->sord = "asc";
			}
		}
		
			
		public function calculatePages($count){
				
			$this->records = $count; //seteo el número de registros
			
			// calculate the total pages for the query 
			if( $this->records > 0 && $this->limit > 0) { 
				$this->total_pages = ceil($this->records/$this->limit); 
			}else{ 
				$this->total_pages = 0;
			}
	
			// if for some reasons the requested page is greater than the total 
			// set the requested page to total page 
			if ($this->page > $this->total_pages) $this->page= $this->total_pages;
		}
		
		public function calculateStart(){ 
				
			//calculate the starting position of the rows 
			$start = $this->limit*$this->page - $this->limit;
			
			//if for some reasons start position is negative set it to 0 
			// typical case is that the user type 0 for the requested page 
			if($start <0) $start = 0;
	
			return $start;
		}
		
		
		public function response($payload){
			// we should set the appropriate header information. Do not forget this.
			header('Cache-Control: no-cache, must-revalidate');
			header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
			header('Content-type: application/json');
	
			$s = "{";
			$s.= "total:\"{$this->total_pages}\",";
			$s.= "page:\"{$this->page}\",";
			$s.= "records:\"{$this->records}\",";
			$s.= "rows:[";
	
			foreach($payload as $id=>$cells){
				
				$s.= "{id:\"".$id."\",cell:[";
				
				for($i=0; $i < count($cells); $i++){
					$s.="\"".$cells[$i]."\"";
					(($i+1) == count($cells)) ? $s.="" : $s.=",";
				}
				$s.="]},"; 	
				
			}
			
			$s .= "]}";
	
			return $s;
				
		}
	
	
	} 
//End JqGrid Request?>
